extends Node2D
class_name  TetrisRegion

@onready var timer:Timer = $Timer
@onready var bottomBlocksArea:BottomBlocksArea = $BottomBlocksArea 

var width = 160
var halfWidth = width / 2
var height = 320
var blockSize = 16
var currentT:Tetromino = null
var randomTypes = ["Type01", "Type02", "Type03", "Type04", "Type05", "Type06", "Type07"]
var randomDirs = {
	"Type01": ["Dir01", "Dir02"],
	"Type02": ["Dir01", "Dir02", "Dir03", "Dir04"],
	"Type03": ["Dir01", "Dir02", "Dir03", "Dir04"],
	"Type04": ["Dir01"],
	"Type05": ["Dir01", "Dir02"],
	"Type06": ["Dir01", "Dir02", "Dir03", "Dir04"],
	"Type07": ["Dir01", "Dir02"]
}

func setPos(pos):
	position = pos
	

func destroyCurrentT():
	if currentT:
		currentT.queue_free()
		currentT = null
	
	
func getSize():
	return Vector2(width, height)


func startGame():
	generateNewTetromino()
	startAutoMoveDown()
	

func gameContinue():
	generateNewTetromino()
	startAutoMoveDown()
	
	
func gameEnd():
	stopAutoMoveDown()


func startAutoMoveDown():
	timer.start()


func stopAutoMoveDown():
	timer.stop()
	

func _on_timer_timeout():
	if currentT != null:
		currentT.moveDown()
	
	
func generateNewTetromino():
	destroyCurrentT()
	
	var targetType = randomTypes[randi_range(0, randomTypes.size()-1)]
	var tergetDir = randomDirs[targetType][randi_range(0, randomDirs[targetType].size()-1)] 
	 
	var inst:Tetromino = Global.createSceneInst("Tetromino") as Tetromino
	add_child(inst)
	inst.setRegion(self)
	inst.initTypeDir(targetType, tergetDir)
	inst.initPos(Vector2(halfWidth, -inst.getHeightOffset()))
	
	currentT = inst
	

func onButtonUpperTrigger():
	if currentT != null:
		currentT.rotateT()


func onRapidButtonLeftTrigger():
	if currentT != null:
		currentT.moveLeft()
	

func onRapidButtonRightTrigger():
	if currentT != null:
		currentT.moveRight()
	

func onRapidButtonDownTrigger():
	if currentT != null:
		currentT.moveDown()
	
	
func testOverlap(blocksData):
	return bottomBlocksArea.testOverlap(blocksData)
	

func add2BottomBlocks(blocksData):
	bottomBlocksArea.addBlocks(blocksData)
	
	
func updateOtherPlayerView(blocksData):
	bottomBlocksArea.updateViewByBlocksData(blocksData)


func getBlocksData():
	var resultBlocksData = []
	
	var currentTBlocksData = null
	if currentT != null:
		currentTBlocksData = currentT.getCurrentBlocksData()
		
	var bottomBlocksData = bottomBlocksArea.getBlocksData()
	
	if currentTBlocksData != null:
		for blockData in currentTBlocksData:
			resultBlocksData.append(blockData)

	if bottomBlocksData != null:
		for blockData in bottomBlocksData:
			resultBlocksData.append(blockData)
			
	return resultBlocksData
	
	

	

